from fastapi import FastAPI, HTTPException, Body
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from pyproj import Transformer
from .routers import airport_rwy
from tortoise.contrib.fastapi import register_tortoise

app = FastAPI()

app.include_router(airport_rwy.router)

TORTOISE_ORM = {
    "connections": {"default": "sqlite://db.sqlite3"},
    "apps": {
        "models": {
            "models": ["src.backend.models", "aerich.models"],
            "default_connection": "default",
        },
    },
}

register_tortoise(
    app,
    config=TORTOISE_ORM,
    generate_schemas=True,
    add_exception_handlers=True,
)

# Add your frontend origins here
origins = [
    "http://localhost",
    "http://localhost:3000",
    "http://localhost:8080",
    "http://localhost:5173",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class Location(BaseModel):
    longitude: float
    latitude: float

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.post("/api/calculateXY")
async def calculate_xy(location: Location = Body(
        default={
            "longitude": 116.397428,
            "latitude": 39.90923
        }
    )):
    if not (72 <= location.longitude < 138):
        raise HTTPException(status_code=400, detail="Longitude is outside the supported range for CGCS2000 projection.")

    # Determine the Gauss-Krüger zone (3-degree)
    zone = int((location.longitude + 1.5) / 3)
    
    # Using a standard EPSG code for the projected CRS is more reliable.
    # CGCS 2000 / Gauss-Krüger zone 38N is EPSG:4547
    # The EPSG codes for 3-degree zones are generally `4525 + zone_number - 13` but this is not robust.
    # A better approach is to use a well-known EPSG code for a given zone.
    # Let's construct the target CRS using an EPSG code if possible.
    # For simplicity and robustness, we will stick to the proj string which is more universal.
    proj_string = f"+proj=tmerc +lat_0=0 +lon_0={zone * 3} +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs"
    
    try:
        transformer = Transformer.from_crs("EPSG:4326", proj_string, always_xy=True)
        x, y = transformer.transform(location.longitude, location.latitude)
        return {"x": x, "y": y}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"An error occurred during coordinate transformation: {e}")


